/**
 * 
 */
package com.giants.common.codec;

import java.security.MessageDigest;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * @author vencent.lu
 *
 */
public class EncryptionDevice {
	
	public static String md5ByBase64Code(String str) throws Exception{
        MessageDigest md5=MessageDigest.getInstance("MD5");
        return new String(Base64.encode(md5.digest(str.getBytes("utf-8"))));
	}
	
	public static String md5ByHexCode(String str) throws Exception{
		MessageDigest md5=MessageDigest.getInstance("MD5");
		return new String(Hex.encode(md5.digest(str.getBytes("utf-8"))));
	}
	
	public static byte[] encryptDES(byte[] data, byte[] key) throws Exception {
		SecureRandom sr = new SecureRandom();
		DESKeySpec dks = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
		return cipher.doFinal(data);
	}
	
	public static String encryptDesByBase64Code(String data, String key) throws Exception{
		return new String(Base64.encode(encryptDES(data.getBytes(), key.getBytes())));
	}
	
	public static String encryptDesByHexCode(String data, String key) throws Exception {
		return new String(Hex.encode(encryptDES(data.getBytes(), key.getBytes())));
	}	
	
	public static String encryptDesByBase64CodeForUrl(String data, String key) throws Exception{
		return Base64.encodeForUrl(encryptDES(data.getBytes(), key.getBytes()));
	}
	
	public static byte[] decryptDES(byte[] data, byte[] key) throws Exception {
		SecureRandom sr = new SecureRandom();
		DESKeySpec dks = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
		return cipher.doFinal(data);
	}
	
	public static String decryptDesByBase64Code(String data, String key) {
		if (data == null) return null;
		try {
			return new String(decryptDES(Base64.decode(data.getBytes()), key.getBytes()));
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String decryptDesByBase64CodeForUrl(String data, String key) {
		if (data == null) return null;
		data = Base64.urlRestoreStanderdBase64(data);
		try {
			return new String(decryptDES(Base64.decode(data.getBytes()), key.getBytes()));
		} catch (Exception e) {
			return null;
		}
	}

}
